package com.ruoyi.web.schedule;

import com.ruoyi.web.domain.MiningRecord;
import com.ruoyi.web.mapper.MiningRecordMapper;
import com.ruoyi.web.utils.IdWorker;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;

/**
 * 挖矿记录造数据
 *
 */
@Component
@EnableScheduling
@AllArgsConstructor
public class MiningRecordTask {

    private final MiningRecordMapper miningRecordMapper;

    private final IdWorker idWorker;

    @Scheduled(fixedDelay = 1000)
    public void recordCheckTask() {
        // 账户 (eth)
        ECKeyPair ecKeyPair;
        try {
            ecKeyPair = Keys.createEcKeyPair();
        } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
        // 公钥
        String ethPublicKey = ecKeyPair.getPublicKey().toString(16);
        // 地址
        String ethAddress = "0x" + Keys.getAddress(ethPublicKey);
        miningRecordMapper.insertMiningRecord(new MiningRecord(){{
            setId(idWorker.nextId());
            setAddress(ethAddress);
            setCreateTime(new Date());
            // 随机数量
            double v = Math.random() * 2000 + 10;
            setNum(new BigDecimal(v).setScale(2, RoundingMode.DOWN));
        }});
        // 删除多余假数据
        miningRecordMapper.deleteLongTimeRecord();
    }

}
